package com.heima.wemedia.delay;

import com.heima.common.delayTask.RedisDelayQueueHandler;
import com.heima.common.delayTask.RedisDelayedQueueUtil;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 初始化 延迟队列
 */
@Slf4j
@Component
public class RedisDealyedQueueInit implements ApplicationContextAware {

    private ApplicationContext context;

    @Autowired
    private RedisDelayedQueueUtil redisDelayedQueueUtil;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    /**
     * 当context 被赋值成功后，真正初始化延迟队列
     */
    @PostConstruct
    public void init(){
        ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(3);

        threadPool.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    Object obj = redisDelayedQueueUtil.getDelayQueue("wm.news.pub");
//                从ioc中拿到实现的类
                    RedisDelayQueueHandler handler =  (RedisDelayQueueHandler)context.getBean("publicNewsDelayHandler");
//                执行延迟队列中获取到的元素,是文章id
                    handler.execute(obj);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        },0,1, TimeUnit.SECONDS);
        log.info("延迟队列已经被监听成功！");

//        在初始化完成后，向队列 添加一个无用的数据
        redisDelayedQueueUtil.addQueue(0,1,TimeUnit.SECONDS,"wm.news.pub");
    }

}
